<?php
namespace plugins\goods\controller;

use app\common\lib\file_operate\FileOperate;
use cmf\controller\PluginAdminBaseController;
use plugins\store\Common;
use think\Db;
use think\Request;

/**
 *
 */
class GoodsCommentController extends PluginAdminBaseController
{
    /**
     * 初始化
     */
    private $com        = '';
    private $pageNum    = "10";
    public $uploadpath  = '';
    public $uploadpaths = '';
    protected function _initialize()
    {
        parent::_initialize();
        $adminId = cmf_get_current_admin_id(); //获取后台管理员id，可判断是否登录
        //dump($adminId);exit;
        if (!empty($adminId)) {
            $this->assign("admin_id", $adminId);
        }
        $this->uploadpath  = ROOT_PATH . 'public' . DS . 'plugins' . DS . 'goods' . DS . 'view' . DS . 'public' . DS . 'image' . DS;
        $this->uploadpaths = ZY_APP_PATH . 'plugins/goods/view/public/image/';
        $this->com         = new Common;
    }
    /**
     * 商品评论列表
     */
    public function index()
    {
        //显示自己店铺评价\平台显示所有
        $param = $this->request->param();
        $where = "is_delete = 0";
        //用户权限判断
        $allow = $this->com->getAllowAccess();
        if ($allow !== true) {
            $where .= " and store_id = '" . $allow . "'";
        }
        //分页传参
        if (!empty($param['store_title'])) {
            $param['search']['store_title'] = $param['store_title'];
        }
        if (!empty($param['store_type'])) {
            $param['search']['store_type'] = $param['store_type'];
        }
        if (!empty($param['goods_title'])) {
            $param['search']['goods_title'] = $param['goods_title'];
        }
        if (!empty($param['goods_type'])) {
            $param['search']['goods_type'] = $param['goods_type'];
        }
        if (!empty($param['user_title'])) {
            $param['search']['user_title'] = $param['user_title'];
        }
        if (!empty($param['user_type'])) {
            $param['search']['user_type'] = $param['user_type'];
        }
        if (!empty($param['start_time'])) {
            $param['search']['start_time'] = $param['start_time'];
        }
        if (!empty($param['end_time'])) {
            $param['search']['end_time'] = $param['end_time'];
        }
        if (!empty($param['report'])) {
            $report = 1;
        }
        //搜索
        $search = [
            "store_title" => isset($param['search']['store_title']) ? $param['search']['store_title'] : "",
            "store_type"  => isset($param['search']['store_type']) ? $param['search']['store_type'] : "",
            "goods_title" => isset($param['search']['goods_title']) ? $param['search']['goods_title'] : "",
            "goods_type"  => isset($param['search']['goods_type']) ? $param['search']['goods_type'] : "",
            "user_title"  => isset($param['search']['user_title']) ? $param['search']['user_title'] : "",
            "user_type"   => isset($param['search']['user_type']) ? $param['search']['user_type'] : "",
            "start_time"  => isset($param['search']['start_time']) ? $param['search']['start_time'] : "",
            "end_time"    => isset($param['search']['end_time']) ? $param['search']['end_time'] : "",
            "report"      => isset($report) ? 1 : "",
        ];
        //查询条件
        if (!empty($search['store_title'])) {
            switch ($search['store_type']) {
                case 1:
                    $where .= " and store_name like '%" . $search['store_title'] . "%'";
                    break;
                case 2:
                    $where .= " and store_id =" . $search['store_title'];
                    break;
            }
        }
        if (!empty($search['goods_title'])) {
            switch ($search['goods_type']) {
                case 1:
                    $where .= " and goods_name like '%" . $search['goods_title'] . "%'";
                    break;
                case 2:
                    $where .= " and goods_id =" . $search['goods_title'];
                    break;
            }
        }
        if (!empty($search['user_title'])) {
            switch ($search['user_type']) {
                case 1:
                    $where .= " and nick_name like '%" . $search['user_title'] . "%'";
                    break;
                case 2:
                    $where .= " and uid =" . $search['user_title'];
                    break;
            }
        }
        if (!empty($search['start_time'])) {
            $where .= " and add_time >=" . strtotime($search['start_time']);
        }
        if (!empty($search['end_time'])) {
            $where .= " and add_time <=" . strtotime($search['end_time']);
        }
        $order = 'add_time desc';
        if (!empty($search['report'])) {
            $where .= " and report >= 1";
            $order .= ",report desc";
            $this->assign('report', $report);
        }
        $sear             = $search;
        $sear['pagesize'] = isset($param['pagesize']) ? $param['pagesize'] : $this->pageNum;
        $data             = db('goods_comment')->where($where)->order($order)->paginates($sear['pagesize'], false, ['query' => $sear]);
        $data->appends($search);
        $this->assign('page', $data->render()); //单独提取分页出来
        $this->assign('search', $search);
        $this->assign('data', $data);
        $this->assign('allow', $allow);
        return $this->fetch('goods_comment/index');
    }
    /**
     *清除举报处理
     */
    public function reset()
    {
        $param = $this->request->post();
        $data  = db('goods_comment')->where('id', $param['id'])->update(['report' => 0]);
        if (!$data) {
            return api_json_echo(false, '操作失败', '', 100);
        }
        return api_json_echo(true, '清除举报', '', 200);
    }
    /**
     *评论图片页
     */
    public function editPage()
    {
        $param = $this->request->param();
        $data  = db('goods_comment')->where('id', $param['id'])->find();
        $img   = json_decode($data['img'], true);
        $this->assign('comment', $data['comment']);
        $this->assign('img', $img);
        return $this->fetch('editPage');
    }
    /**
     * 删除评论-软删
     */
    public function delete()
    {
        $param = $this->request->post();
        if (empty($param['id'])) {
            return api_json_echo(false, '未选择数据', '', 100);
        }
        $id = $param['id'];
        if (is_array($id)) {
            $data = db('goods_comment')->where('id', 'in', $id)->update(['is_delete' => 1]);
        } else {
            $data = db('goods_comment')->where('id', $id)->update(['is_delete' => 1]);
        }
        return api_json_echo(true, '操作成功', '', 200);
    }
    /**
     * 评论配置页
     */
    public function configPage()
    {
        $allow = $this->com->getAllowAccess();
        if ($allow == true) {
            $allow = 'comment';
        }
//平台
        //读取平台配置
        $config = json_decode(getModuleConfig('comment', 'data/config', 'comment.json'), true);
        //读取当前店铺配置
        $info = json_decode(getModuleConfig('comment', 'data/config', $allow . '.json'), true);
        if ($info) {
            //遍历平台与店铺配置保留相同配置替换新配置
            foreach ($config as $key => $value) {
                if ($value['is_show'] !== '0') {
                    foreach ($info as $in) {
                        if ($value['name'] == $in['name']) {
                            $config[$key] = $in;
                        }
                    }
                } else {
                    unset($config[$key]); //删除平台关闭的配置
                }
            }
        }
        //重新保存配置-店铺未配置存平台配置
        saveModuleConfigData('comment', 'data/config', $allow . '.json', $config);
        $this->assign('data', $config);
        return $this->fetch('configPage');
    }
    /**
     * 保存评论配置
     */
    public function commentConfig()
    {
        $param = $this->request->post();
        $allow = $this->com->getAllowAccess();
        if ($allow == true) {
            $allow = 'comment';
        }
        //平台comment
        $config = json_decode(getModuleConfig('comment', 'data/config', $allow . '.json'), true);
        foreach ($config as $key => $value) {
            $value['is_show'] = isset($param[$value['name']]) ? $param[$value['name']] : "0";
            $config[$key]     = $value;
        }
        $data = saveModuleConfigData('comment', 'data/config', $allow . '.json', $config);
        if (!empty($data)) {
            return api_json_echo(true, '配置成功', '', 200);
        }
        return api_json_echo(false, '配置失败', '', 100);
    }
    /**
     * 查看回复
     */
    public function replyPage()
    {
        $param = $this->request->param();
        $data  = db('goods_comment_reply')->where('cid', $param['id'])->select()->each(function($item){
            if($item['reply_type']==1){
                $user = db('member')->where('uid',$item['uid'])->field('uid,nick_name,head_portrait')->find();
                $item['uid'] = $user['uid'];
                $item['nick_name'] = $user['nick_name'];
                $item['head_portrait'] = $user['head_portrait'];  
            }else{              
                $store = db('store')->where('store_id',$item['uid'])->field('store_id,store_name,store_log')->find();
                $item['uid'] = $store['store_id'];
                $item['nick_name'] = $store['store_name'];
                $item['head_portrait'] = $store['store_log'];  
            }
            return $item;
        
        });
        $this->assign('data', $data);
        return $this->fetch('replyPage');
    }
    /**
     * 回复评论
     */
    public function reply()
    {
        $param = $this->request->post();
        if (empty($param['id'])) {
            return api_json_echo(false, '请先选择需要回复的评论', '', 100);
        }
        $value = 2; //店铺回复、3平台回复
        $allow = $this->com->getAllowAccess();
        if ($allow == true) {
            $value = 3;
            $allow = 'admin';
        }
        
        $id = $param['id'];
        if (is_array($id)) {
            foreach ($id as $key_s => $val_s) {
                $add = [
                    'cid'        => $val_s,
                    'comment'    => $param['comment'],
                    'add_time'   => time(),
                    'reply_type' => $value, //回复端
                    'uid'        => $allow //店铺平台

                ];
                //查头像昵称
                $data = db('goods_comment_reply')->insert($add);
                db('goods_comment')->where('id', $val_s)->setInc('reply');
            }
        } else {
            //平台comment
            $add = [
                'cid'        => $id,
                'comment'    => $param['comment'],
                'add_time'   => time(),
                'reply_type' => $value, //回复端
                'uid'        => $allow //店铺平台
            ];
            //查头像昵称
            $data = db('goods_comment_reply')->insert($add);
            db('goods_comment')->where('id', $id)->setInc('reply');
            if (!$data) {
                return api_json_echo(false, '回复失败', '', 100);
            }
        }
        return api_json_echo(true, '回复成功', '', 200);
    }
    /**
     * 上传图片
     */
    public function upload()
    {
        $data        = $this->request->param();
        $file        = $_FILES['file'];
        $app         = $data['_plugin'];
        $upload_path = "/plugins/" . $app . "/view/public/img/catimg/";
        $fo          = new FileOperate();
        $res         = $fo->uploadImg($file, $upload_path);
        if ($res['status'] == false) {
            return api_json_echo(false, '上传失败' . $res['message'], '', 100);
        }
        return api_json_echo(true, '上传成功', $res['data'], 200);
    }
    /**
     *商品主图上传/商品详情图
     */
    public function uploadimg()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');
        //exit(dump($file));
        // 移动到框架应用根目录/public/uploads/ 目录下
        if ($file) {
            if (input('type')) {
                $outpath = $this->uploadpath . 'goodsinfo';
            } else {
                $outpath = $this->uploadpath . 'goodsimg';
            }
            $info = $file->move($outpath);
            if ($info) {
                // 成功上传后 获取上传信息
                // 输出 jpg
                //echo $info->getExtension();
                // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                $data = [
                    'code' => 0,
                    'msg'  => '',
                    'data' => [
                        'src' => str_replace("\\", "/", $info->getSaveName()),
                    ],
                ];
                return $data;
                // 输出 42a79759f284b767dfcb2a0197904287.jpg
                //echo $info->getFilename();
            } else {
                // 上传失败获取错误信息
                return $file->getError();
            }
        }
    }
    /**
     *商品相册图上传
     */
    public function uploadthumb()
    {
        $fileKey = key($_FILES);
        $file    = request()->file($fileKey);
        //exit(dump($file));
        // 移动到框架应用根目录/public/uploads/ 目录下
        if ($file) {
            $outpath = $this->uploadpath . 'goodsthumb';
            $info    = $file->move($outpath);
            if ($info) {
                // 成功上传后 获取上传信息
                // 输出 jpg
                //echo $info->getExtension();
                // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                $data = [
                    'jsonrpc' => "2.0",
                    'result'  => [
                        'src' => str_replace("\\", "/", $info->getSaveName()),
                    ],
                    'name'    => $info->getFilename(),
                ];
                exit(json_encode($data));
                // 输出 42a79759f284b767dfcb2a0197904287.jpg
                //echo $info->getFilename();
            } else {
                // 上传失败获取错误信息
                $data = [
                    'jsonrpc' => "2.0",
                    'error'   => [
                        'code'    => '102',
                        'message' => $file->getError(),
                    ],
                ];
                exit(json_encode($data));
            }
        }
    }
}
